package cl.ucn.disc.biblio.refcluster.reference;

import java.text.ParseException;

import cl.ucn.disc.biblio.refcluster.database.TupleOfStrings;

public class Author implements TupleOfStrings<Author> {
	@Override
	public String toString() {
		return getString();
	}

	private String unprocessedString;
	
	private String first;
	private String last;
	
	public Author() {
		
	}
	
	public Author(String str) throws ParseException {
		parse(str);
	}

	public static boolean isFormatFirstUpperCaseWithCommas(String string) {
		return string.indexOf(',') >= 0;
	}
	
	
	@Override
	public void parse(String str) throws ParseException {
		unprocessedString = str;
		String[] data;
		if (isFormatFirstUpperCaseWithCommas(str)) {
			data = str.split(",");
			last = data[0].trim().toUpperCase();
			first = data[1].trim().toUpperCase();
		} else if (str.indexOf(' ') != -1){
			data = str.split(" ");
			last = data[0].trim().toUpperCase();
			first = data[1].trim().toUpperCase();
		} else {
			last = str;
			first = "";
		}
		
		

	}

	@Override
	public String getString() {
		return formatUpperCaseNoCommas();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((first == null) ? 0 : first.hashCode());
		result = prime * result + ((last == null) ? 0 : last.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Author other = (Author) obj;
		if (first == null) {
			if (other.first != null)
				return false;
		} else if (!first.equals(other.first))
			return false;
		if (last == null) {
			if (other.last != null)
				return false;
		} else if (!last.equals(other.last))
			return false;
		return true;
	}

	@Override
	public String getUnprocessedString() {
		return unprocessedString;
	}
	
	public String formatUpperCaseNoCommas() {
		return (last.toUpperCase().replaceAll("\\s+", "").replaceAll("\\-+", "") + " " + first.toUpperCase()).trim();
	}
	
	public String formatFirstUpperCaseWithCommas() {
		return (last.substring(0,1).toUpperCase() + last.substring(1).toLowerCase() + ", " + first.toUpperCase()).trim();
	}

	@Override
	public int compareTo(Author o) {
		return getString().compareTo(o.getString());
	}
}
